package org.utils.util;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

/**
 * List Utilities
 */
public class ListUtils
{
  /**
   * Insert the object in the case insensitive order in the list
   * using the String CASE_INSENSITIVE_ORDER Comparator Class.
   *
   * @see #insertSorted(List, Object, Comparator, boolean)
   *
   * @param list The list to add the object
   * @param obj The object to add
   */
  public static void insertSorted(List list, Object obj)
  {
    if (obj instanceof String)
      insertSorted(list, obj, String.CASE_INSENSITIVE_ORDER, true);
    else
      throw new IllegalArgumentException("Object is not of type String, you must supply a Comparator");
  }

  /**
   * Insert the object in the list in the order implied by the comparator.
   *
   * @see #insertSorted(List, Object, Comparator, boolean)
   *
   * @param list The list to add the object
   * @param obj The object to add
   * @param c The comparator to use for inserting the object to the right place
   */
  public static void insertSorted(List list, Object obj, Comparator c)
  {
    insertSorted(list, obj, c, true);
  }

  /**
   * Insert the object in the list in the order implied by the comparator.
   *
   * @param list The list to add the object
   * @param obj The object to add
   * @param c The comparator to use for inserting the object to the right place
   * @param acceptDuplicateObject Allow or not the duplicate object in the list
   */
  public static void insertSorted(List list, Object obj, Comparator c, boolean acceptDuplicateObject)
  {
    for (int i = 0; i < list.size(); i++)
    {
      int value = c.compare(list.get(i), obj);
      if (value == 0)
      {
		if (acceptDuplicateObject)
	  		list.add(i, obj);
		return ;
      }
      if (value > 0)
      {
		list.add(i, obj);
		return ;
      }
    }
    list.add(obj);
  }
  /**
   * 
   * @param src
   * @param i
   * @param j
   * @return List
   */
  public static List subList(List src, int i, int j)
  {
  	List sublist = new LinkedList();
  	for (int index = i; index < j; index++)
  	{
		sublist.add(src.get(index));
  	}
  	return sublist;
  }
}
